<template>
  <div class="app-container">
    <!-- 用户详情弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        title="用户详情"
        width="30%"
        center
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="用户名">{{ userDetail.username }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ userDetail.email }}</el-descriptions-item>
        <el-descriptions-item label="用户角色">
          <el-tag :class="'role-tag role-' + userDetail.role">
            {{ userDetail.role === 'admin' ? '管理员' : '普通用户' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="注册时间">{{ userDetail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="最后登录">{{ userDetail.lastLogin }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <!-- 筛选区域 -->
    <div class="action-bar">
      <h2 class="page-title">用户列表</h2>
      <el-form :model="filter" class="filter-container" inline>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="filter.username" placeholder="请输入用户名" clearable />
        </el-form-item>

        <el-form-item label="用户角色" prop="role">
          <el-select v-model="filter.role" placeholder="请选择角色" clearable>
            <el-option
                v-for="item in roleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="filter-actions">
          <el-button @click="resetFilter">重置</el-button>
          <el-button type="primary" @click="search">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="handleAddUser">添加用户</el-button>

    </div>


    <el-table
        :data="list"
        style="width: 100%"
        border
        fit
        highlight-current-row
        :header-cell-style="{ background: '#f5f7fa', fontWeight: 'bold' }"
    >
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="username" label="用户名" width="auto" align="center" />
      <el-table-column label="角色" width="auto" align="center">
        <template #default="scope">
          <el-tag :class="'role-tag role-' + scope.row.role" effect="dark">
            {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="collection" label="收藏" width="auto" align="center" />
      <el-table-column prop="comment" label="评论" width="auto" align="center" />
      <el-table-column prop="email" label="邮箱" width="auto" align="center" />
      <el-table-column label="操作" width="220" align="center">
        <template #default="scope">
          <div class="action-buttons">
            <el-button type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="warning" size="small" @click="handelEdit(scope.row)">编辑</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination align="center"
                   background
                   layout="total, prev, pager, next"
                   :total="totalCount"
                   :page-size="pageSize"
                   :current-page="currentPage"
                   @current-change="handlePageChange"
                   class="pagination-container"
    />
  </div>
</template>

<script>export default {

  data() {
    return {
      dialogVisible: false,
      userDetail: {
        username: '',
        email: '',
        role: '',
        createTime: '',
        lastLogin: ''
      },
      list: [],
      totalCount: 0,
      pageSize: 5,
      currentPage: 1,
      filter: {
        username: '',
        role: ''
      },
      roleOptions: [
        { value: 'admin', label: '管理员' },
        { value: 'user', label: '普通用户' }
      ]
    }
  },
  created() {
    this.fetchUserList()
  },
  methods: {
    handleAddUser() {
      this.$router.push('/apiusers/add');
    },
    fetchUserList() {
      this.$axios.get('/user/list', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...(this.filter.username && {userName: this.filter.username}),
          ...(this.filter.role && {userType: this.filter.role === 'admin' ? 0 : 1})
        }
      }).then(res => {
        this.list = res.data.data.list.map(item => ({
          id: item.id,
          username: item.userName,
          role: item.userType === 0 ? 'admin' : 'user',
          collection: '-',
          comment: '-',
          email: item.email,
        }))
        this.totalCount = res.data.data.total
      })
    },
    search() {
      this.fetchUserList()
      // 刷新到第一页
      this.currentPage = 1
    },
    resetFilter() {
      this.filter = {
        username: '',
        role: ''
      }
      this.fetchUserList()
    },
    handleView(row) {
      this.$axios.get(`/user/info/${row.id}`).then(res => {
        if (res.data.code !== 200) {
          this.$message.error('获取用户信息失败');
          return;
        }
        const data = res.data.data;
        this.userDetail = {
          username: data.user.userName,
          email: data.user.email,
          role: data.user.userType === 0 ? 'admin' : 'user',
          createTime: "功能开发中",
          lastLogin: "功能开发中"
        };
        this.dialogVisible = true;
      }).catch(error => {
        console.error('获取用户信息失败:', error);
      });

    },
    handleDelete(row) {
      this.$axios.post(`/user/delete/${row.id}`).then(res => {
        if (res.data.code !== 200) {
          this.$message.error('删除用户失败');
          return;
        }
        //加点弹窗让用户是否删除提示
        this.$confirm('确定要删除该用户吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
            .then(() => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.fetchUserList()
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              })
            })
      }).catch(error => {
        console.error('删除用户失败:', error);
      })
    },
    handelEdit(row) {
      this.$router.push(`/apiusers/edit/${row.id}`);
    },
    handlePageChange(page) {
      this.currentPage = page
      this.fetchUserList()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  margin-bottom: 20px;
}

.filter-container {
  flex-grow: 1;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.filter-actions {
  margin-left: auto;
}

.el-form-item {
  margin-bottom: 0 !important;
  margin-right: 0 !important;
}

.page-title {
  font-size: 18px;
  color: #303133;
}

.filter-container {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}

.filter-actions {
  display: flex;
  gap: 10px;
}

.el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  padding-right: 20px;
}

.action-buttons {
  display: flex;
  flex-direction: row;
  justify-content: center;
  gap: 8px;
}

.el-button + .el-button {
  margin-left: 0px;
}

/* 修复的样式部分 */
:deep(.el-table th) {
  /* 表头样式 */
  background-color: #f5f7fa !important;
}

:deep(.el-table__row) {
  height: 60px;
}

:deep(.el-table__header) {
  background-color: #f5f7fa !important;
  color: #606266;
  border-radius: 4px 4px 0 0;
}

.role-tag {
  margin: 2px 5px;
  font-weight: bold;
  min-width: 70px;
  text-align: center;
  border-radius: 12px;
}

.role-tag.role-admin {
  background-color: #ecf5ff;
  color: #409eff;
  border-color: #d9ecff;
}

.role-tag.role-user {
  background-color: #f0f9eb;
  color: #67c23a;
  border-color: #e1f3d8;
}

:deep(.el-form-item .el-select) {
  min-width: 120px;
}

:deep(.el-select__input-wrapper.is-hidden) {
  opacity: 0;
  z-index: -1;
}
</style>
